package com.gxa.park.core.util;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;

/**
 * @author Min
 */
public class RemoteUtil {

    private static final RestTemplate restTemplate=new RestTemplate();
    /**
     * 发送远程请求
     * @param url 请求地址
     * @param type 请求头类型
     * @param responseType 返回值类型
     * @param params 请求参数
     * @param <T>
     * @return
     */
    public static<T> T  RemotePostHttp(String url, MediaType type, Class<T> responseType, Map<String,Object> params){

        HttpEntity objectHttpEntity = getHttpEntity(type,params);

        // 发送请求
        T t = restTemplate.postForObject(url,objectHttpEntity,responseType);

        return t;
    }


    private static HttpEntity getHttpEntity(MediaType type, Map<String, Object> params) {
        // 创建参数存储列表
        MultiValueMap<String, Object> stringMuil = new LinkedMultiValueMap<>();

        // 遍历设置当前参数
        Set<String> keys = params.keySet();

        for (String key : keys) {
            stringMuil.add(key, params.get(key));
        }

        // 设置请求头 发送类型
        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.setContentType(type);

        //  设置请求体
        HttpEntity objectHttpEntity = new HttpEntity(stringMuil,httpHeaders);
        return objectHttpEntity;
    }
}
